package com.guodi.model.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guodi.common.utils.AjaxResult;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.model.entity.ApiIdtIndicatorsDir;
import com.guodi.model.entity.ApiIndicatorsVal;
import com.guodi.model.entity.IdtIndicators;
import com.guodi.model.entity.IdtIndicatorsType;
import com.guodi.model.mapper.IdtIndicatorsDirMapper;
import com.guodi.model.mapper.MonitorEvaluateWarningMapper;
import com.guodi.model.service.IIdtIndicatorsDirService;
import com.guodi.model.service.IIdtIndicatorsService;
import com.guodi.model.service.IIdtIndicatorsTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @描述：监测评估预警
 * @作者: 戴伙进
 * @日期: 2020/6/30 11:05
 */
@RestController
@RequestMapping("/MonitorEvaluateWarning")
@Api(value = "API - MonitorEvaluateWarningController", description = "监测预警评估指标查询")
public class MonitorEvaluateWarningController extends BaseController {

    @Resource
    private IIdtIndicatorsTypeService iIdtIndicatorsTypeService;

    @Resource
    public IIdtIndicatorsDirService idtIndicatorsDirService;

    @Resource
    private IIdtIndicatorsService iIdtIndicatorsService;

    @Resource
    private IdtIndicatorsDirMapper idtIndicatorsDirMapper;

    @Resource
    private MonitorEvaluateWarningMapper monitorEvaluateWarningMapper;

    @PostMapping("/listIndicatorsMonitorByCode")
    @ApiOperation(value = "监测评估预警-动态监测--指标预警")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "指标体系编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "keyWord", value = "关键字搜索", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "机构id(65fc1451aa4640c795b971ae9199456c)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "particularYear", value = "指标体系年份", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult listIndicatorsMonitorByCode(String code, String keyWord, String year, String divisionCode, String orgId, String particularYear) {
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(code, particularYear, divisionCode);
        if(one == null){
            return new AjaxResult();
        }
        //获取父节点下的所有数据
        List<ApiIdtIndicatorsDir> treeList = idtIndicatorsDirService.listDirByCode(one.getId(), null, null);
        if (treeList != null && treeList.size() > 0) {
            // 过滤掉关联的指标已经被删除了的记录
            LambdaQueryWrapper<IdtIndicators> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(IdtIndicators::getId);
            List<Map<String, Object>> maps = this.iIdtIndicatorsService.listMaps(queryWrapper);
            List<String> allIdtIdList = maps.stream().map(map -> {
                return map.containsKey("id") ? map.get("id").toString() : map.get("ID").toString();
            }).collect(Collectors.toList());
            treeList = treeList.parallelStream().filter(dir->{
                return dir.getType() != 2 ? true: allIdtIdList.contains(dir.getIndicatorsId());
            }).collect(Collectors.toList());

            // 查询指标数值
            // 获取所有指标
            List<String> idtIdList = treeList.stream().filter(idtDir -> {
                return idtDir.getType() == 2;
            }).map(ApiIdtIndicatorsDir::getIndicatorsId).collect(Collectors.toList());
            if (idtIdList.isEmpty()){
                return new AjaxResult(createTree(one.getId(), treeList));
            }
            // 查指标数值
            Map<String, List<ApiIndicatorsVal>> idtValMap = iIdtIndicatorsService.mapIdtVal(idtIdList, year, divisionCode, false, false);

            // 填入对象中
            treeList.stream().filter(idtDir -> {
                return idtDir.getType() == 2;
            }).forEach(idtDir -> {
                List<ApiIndicatorsVal> apiIndicatorsValList = idtValMap.get(idtDir.getIndicatorsId());
                if (apiIndicatorsValList != null && !apiIndicatorsValList.isEmpty()){
                    ApiIndicatorsVal idtVal = apiIndicatorsValList.get(0);
                    // 20210803新增指标预警规则判断，动态更新指标监测值预警状态
                    if(StringUtils.isNotBlank(idtVal.getWarnRuleConfig())){
                        String warnStatus = iIdtIndicatorsService.updateWarnStatus(idtVal);
                        idtVal.setWarnStatus(warnStatus);
                    }else {
                        idtVal.setWarnStatus("null,尚未配置规则");
                    }
                    idtDir.setApiIndicatorsVal(idtVal);
                }
            });
        }
        //创建树形结构
        List tree;
        if (StringUtils.isNotBlank(keyWord)) {
            List<ApiIdtIndicatorsDir> keyWordList = getListRecordByKeywords(treeList, keyWord,false);
            tree = createTree(one.getId(), keyWordList);
            treeList = keyWordList;
        } else {
            tree = createTree(one.getId(), treeList);
        }
        //加统计数据
        for (int i = 0; i < tree.size(); i++) {
            ApiIdtIndicatorsDir apiIdtIndicatorsDir = (ApiIdtIndicatorsDir) tree.get(i);
            String id = apiIdtIndicatorsDir.getId();
            Integer sumIndicators = idtIndicatorsDirMapper.getIndicatorsCount(id, null, keyWord);
            //获取父节点下的所有数据
            List<ApiIdtIndicatorsDir> compareList = idtIndicatorsDirService.listDirByCode(id, null, keyWord);
            Integer sumWarnStatus = queryWarnStatusSum(compareList, treeList);
            apiIdtIndicatorsDir.setSumIndicators(sumIndicators);
            apiIdtIndicatorsDir.setSumWarnStatus(sumWarnStatus);
        }
        return new AjaxResult(tree);
    }

    /**
     * @描述:获取指标最近的更新记录
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/7/6 17:05
     **/
    @PostMapping("/listAllByRecentTime")
    @ApiOperation(value = "获取指标最近更新的相关记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "divisionCode", value = "行政区划编码", required = true, dataType = "string", paramType = "query"),
    })
    public AjaxResult listAllByRecentTime(String divisionCode) {
        List<ApiIndicatorsVal> list = monitorEvaluateWarningMapper.getAllByOneMonth(divisionCode);
        if (list.size() < 10) {
            list = monitorEvaluateWarningMapper.getNumByTime(10, divisionCode);
        }
        return new AjaxResult(list);
    }

    /**
     * @描述:通过关键字找到列表数据
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/7/7 15:34
     **/
    public List<ApiIdtIndicatorsDir> getListRecordByKeywords(List<ApiIdtIndicatorsDir> allRecords, String keywords, boolean bolWarning) {
        List<ApiIdtIndicatorsDir> listRecord = new ArrayList<>();
        Map<String, ApiIdtIndicatorsDir> allRecordMap = new HashMap<>();
        for (ApiIdtIndicatorsDir record : allRecords) {
            allRecordMap.put(record.getId(), record);
        }
        if(bolWarning){
            //遍历所有的记录找出所有的nodeName和关键字keywords的相关数据
            if (allRecords != null && allRecords.size() > 0) {
                for (ApiIdtIndicatorsDir record : allRecords) {
                    if ("".equals(keywords)) {
                        if (record.getApiIndicatorsVal() != null) {
                            //比较
                            if ("预警".equals(record.getApiIndicatorsVal().getWarnStatus()) && record.getType() == 2) {
                                listRecord.add(record);
                            }
                        }
                    } else {
                        if (record.getApiIndicatorsVal() != null) {
                            //比较
                            if ("预警".equals(record.getApiIndicatorsVal().getWarnStatus()) && record.getName().toLowerCase().indexOf(keywords.toLowerCase()) != -1 && record.getType() == 2) {
                                listRecord.add(record);
                            }
                        }
                    }
                }
            }
        }else {
            //遍历所有的记录找出所有的nodeName和关键字keywords的相关数据
            if (allRecords != null && allRecords.size() > 0) {
                for (ApiIdtIndicatorsDir record : allRecords) {
                    if ("".equals(keywords)) {
                        if (record.getApiIndicatorsVal() != null) {
                            //比较
                            if (record.getType() == 2) {
                                listRecord.add(record);
                            }
                        }
                    } else {
                        if (record.getApiIndicatorsVal() != null) {
                            //比较
                            if (record.getName().toLowerCase().indexOf(keywords.toLowerCase()) != -1 && record.getType() == 2) {
                                listRecord.add(record);
                            }
                        }
                    }
                }
            }
        }
        //查找过滤出来的节点和他们的父节点
        listRecord = this.getSelfAndTheirParentRecord(listRecord, new ArrayList<>(), new HashMap<>(), allRecordMap);
        return listRecord;
    }

    /**
     * @描述:递归找出本节点和他们的父节点
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/7/7 15:16
     **/
    private List<ApiIdtIndicatorsDir> getSelfAndTheirParentRecord(List<ApiIdtIndicatorsDir> parentList, List<ApiIdtIndicatorsDir> resultList, Map<String, ApiIdtIndicatorsDir> filterRecordMap, Map<String, ApiIdtIndicatorsDir> allRecordMap) {
        //当父节点为null或者节点数量为0返回结果，退出递归
        if (parentList == null || parentList.size() == 0) {
            return resultList;
        }
        //重新创建父节点集合
        List<ApiIdtIndicatorsDir> listParentRecord = new ArrayList<>();
        //遍历已经过滤出来的
        for (ApiIdtIndicatorsDir record : parentList) {
            String id = record.getId();
            String parent_id = record.getParentId();
            //已经过滤出来的的节点不存在则添加到list中
            if (!filterRecordMap.containsKey(id)) {
                listParentRecord.add(record);
                filterRecordMap.put(id, record);
                allRecordMap.remove(id);
                resultList.add(record);
            }
            //找出本节点的父节点病添加到listParentRecord父节点集合中，并移除集合中对应的元素
            if (StringUtils.isNotBlank(parent_id)) {
                ApiIdtIndicatorsDir parentRecord = allRecordMap.get(parent_id);
                if (parentRecord != null) {
                    listParentRecord.add(parentRecord);
                    allRecordMap.remove(parent_id);
                }
            }
        }
        //递归调用
        getSelfAndTheirParentRecord(listParentRecord, resultList, filterRecordMap, allRecordMap);
        return resultList;
    }

    /**
     * @描述:创建树
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/7/6 11:18
     **/
    public static List createTree(String parentId, List<ApiIdtIndicatorsDir> menus) {
        List tree = new ArrayList<>();
        for (int i = 0; i < menus.size(); i++) {
            ApiIdtIndicatorsDir idtDirectory = menus.get(i);
            if (idtDirectory.getParentId().equals(parentId)) {
                tree.add(idtDirectory);
                List children = createTree(idtDirectory.getId(), menus);
                if (children != null && !children.isEmpty()) {
                    idtDirectory.setChildren(children);
                }
            }
        }
        return tree;
    }

    /**
     * @描述:查询监测预警预警状态总数
     * @入参:
     * @出参:
     * @作者: 戴伙进
     * @日期: 2020/7/7 9:44
     **/
    public int queryWarnStatusSum(List<ApiIdtIndicatorsDir> compareList, List<ApiIdtIndicatorsDir> allList) {
        int sum = 0;
        for (int i = 0; i < compareList.size(); i++) {
            ApiIdtIndicatorsDir compareApiIdtIndicatorsDir = compareList.get(i);
            for (int j = 0; j < allList.size(); j++) {
                ApiIdtIndicatorsDir allListApiIdtIndicatorsDir = allList.get(j);
                if (compareApiIdtIndicatorsDir.getId().equals(allListApiIdtIndicatorsDir.getId())) {
                    if (allListApiIdtIndicatorsDir.getApiIndicatorsVal() != null) {
                        if (allListApiIdtIndicatorsDir.getApiIndicatorsVal().getWarnStatus().contains("预警")) {
                            sum++;
                        }
                    }
                }
            }
        }
        return sum;
    }

   /* *//**
    * @描述: 导出监测数据
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/10/30 15:27
    **//*
    @PostMapping("/exportExcel")
    @ApiOperation(value = "导出监测数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "指标体系编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "keyWord", value = "关键字搜索", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "机构id(65fc1451aa4640c795b971ae9199456c)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "particularYear", value = "指标体系年份", required = true, dataType = "string", paramType = "query")
    })
    public void exportExcel(String code, String keyWord, String year, String divisionCode, String orgId, String particularYear)throws Exception{
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(code, particularYear, divisionCode);
        //获取父节点下的所有数据
        List<ApiIdtIndicatorsDir> apiIdtIndicatorsDirs = idtIndicatorsDirService.listDirByCode(one.getId(), null, null);
        if (apiIdtIndicatorsDirs != null && apiIdtIndicatorsDirs.size() > 0) {
            for (ApiIdtIndicatorsDir idtDir : apiIdtIndicatorsDirs) {
                if (idtDir.getType() == 2) {
                    ApiIndicatorsVal apiIndicatorsVal = iIdtIndicatorsService.getIdtVal(idtDir.getIndicatorsId(), year, divisionCode, false, false);
                    IdtWarnRule idtWarnRule = iIdtWarnRuleService.listWarnRuleById(idtDir.getIndicatorsId());
                    apiIndicatorsVal.setParentName(idtDir.getParentName());
                    if (null != idtWarnRule) {
                        apiIndicatorsVal.setWarnRule(idtWarnRule.getName());
                    } else {
                        apiIndicatorsVal.setWarnRule(null);
                    }
                    idtDir.setApiIndicatorsVal(apiIndicatorsVal);
                }
            }
        }
        //获取需要导出的数据
        List<ApiIndicatorsVal> apiIdtIndicatorsDirList = apiIdtIndicatorsDirs.stream().filter(x ->x.getType()==2).map(x ->x.getApiIndicatorsVal()).collect(Collectors.toList());
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(new Date());
        ExcelUtil.exportExcel(apiIdtIndicatorsDirList, "监测数据-列表", "监测数据表", ApiIndicatorsVal.class,
                URLEncoder.encode("IdtIndicatorsDir-log", "UTF-8")+ dateStr, response);

    }

    *//**
    * @描述: 监测评估预警-指标预警--导出报告
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/11/24 10:58
    **//*
    @PostMapping("/exportIndicatorsMonitorReport")
    @ApiOperation(value = "监测评估预警-指标预警--导出报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "指标体系编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "机构id(65fc1451aa4640c795b971ae9199456c)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "particularYear", value = "指标体系年份", required = true, dataType = "string", paramType = "query")
    })
    public AjaxResult exportIndicatorsMonitorReport(String code, String year, String divisionCode, String orgId, String particularYear) {
        if (StringUtils.isBlank(code)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "请传入编码");
        }
        if (StringUtils.isBlank(orgId)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "请传入机构");
        }
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(code, particularYear, divisionCode);
        //获取父节点下的所有数据
        List<ApiIdtIndicatorsDir> treeList = idtIndicatorsDirService.listDirByCode(one.getId(), orgId, null);
        if (treeList != null && treeList.size() > 0) {
            for (ApiIdtIndicatorsDir idtDir : treeList) {
                if (idtDir.getType() == 2) {
                    ApiIndicatorsVal apiIndicatorsVal = iIdtIndicatorsService.getIdtVal(idtDir.getIndicatorsId(), year, divisionCode, false, false);
                    idtDir.setApiIndicatorsVal(apiIndicatorsVal);
                }
            }
        }
        //创建树形结构
        List tree = createTree(one.getId(), treeList);
        String ftpFileName;
        String exportTempFileName = null;
        try {
            //筛选下数据
            List newTreeList = new ArrayList();
            for (int i = 0; i < tree.size(); i++) {
                ApiIdtIndicatorsDir apiIdtIndicatorsDir = (ApiIdtIndicatorsDir) tree.get(i);
                List<ApiIdtIndicatorsDir> listChildren = apiIdtIndicatorsDir.getChildren();
                for (int j = 0; j < listChildren.size(); j++) {
                    ApiIdtIndicatorsDir apiIdtIndicatorsDir1 = listChildren.get(j);
                    if ("constraint".equals(apiIdtIndicatorsDir1.getApiIndicatorsVal().getAttribute())) {
                        newTreeList.add(apiIdtIndicatorsDir);
                        break;
                    }
                }
            }

            PageData pageData = new PageData();
            List<PageData> divisionList = planStatusQuoService.listDivisionByEntity(pageData);
            Map<String, String> dictMap = new HashMap<>();
            for (PageData data : divisionList) {
                dictMap.put(data.get("code").toString(), data.get("name").toString());
            }

            String exportFileName = exportIndicatorsMonitorWord(newTreeList, divisionCode, year, dictMap);
            exportTempFileName = FileUtil.tempFilePath + exportFileName;
            InputStream inputStream = new FileInputStream(exportTempFileName);
            String newExportFileName = "国土空间规划监测预警报告_" + System.currentTimeMillis() + ".docx";

            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            ftpFileName = FastDFSUtil.upload( output.toByteArray(), "docx");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new AjaxResult(StatusCode.REQUEST_CODE_OPERATION_FAILURE, e.getMessage());
        } finally {
            //删除临时文件
            FileUtil.deleteFile(exportTempFileName);
        }
        return new AjaxResult(ftpFileName);
    }

    *//**
    * @描述:导出监测预警报告,返回文件的名称
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/11/24 11:27
    **//*
    public String exportIndicatorsMonitorWord(List tree, String divisionCode, String year, Map<String, String> dictMap) {
        String exportFilePath = null;
        String divisionLevel = "";
        String divisionCodeNoZero = divisionCode.replaceAll("0+$", "");
        if (divisionCodeNoZero.length() <= 2) {
            divisionLevel = "省";
        } else if (divisionCodeNoZero.length() <= 6) {
            divisionLevel = "市";
        } else {
            divisionLevel = "县";
        }
        //获取行政区划文本名称
        String divisionText = dictMap.get(divisionCodeNoZero);
        //插入的html内容
        String html_str = "";
        html_str += ("<style>\n" +
                "table,td,th{\n" +
                "\tfont-size:12px;\n" +
                "\tborder:1px solid grey;\n" +
                "\tpadding:5px;\n" +
                "\twidth:555px;\n" +
                "\ttext-align:center;\n" +
                "}\n" +
                "</style>");
        try {
            //导出监测报告
            List<Map<String, Object>> table2 = new ArrayList<>();
            //域字段
            List<Map<String, Object>> fieldData = new ArrayList<>();
            Integer xh = 0;
            List<Integer> keyXh = new ArrayList<>();
            //预警指标项
            Integer warningNumber = 0;
            for (int i = 0; i < tree.size(); i++) {
                ApiIdtIndicatorsDir apiIdtIndicatorsDir = (ApiIdtIndicatorsDir) tree.get(i);
                String bigName = apiIdtIndicatorsDir.getName();
                List<ApiIdtIndicatorsDir> listChildren = apiIdtIndicatorsDir.getChildren();
                String bigXh = ConvertUtil.ToCH((i + 3));
                //只添加约束性指标
                html_str += ("<h2 style=\"font-family:'宋体';font-size:18px\">" + bigXh + "、" + bigName + "</h1>\n");
                Integer zxh = 0;
                keyXh.add(xh);
                for (int j = 0; j < listChildren.size(); j++) {
                    ApiIdtIndicatorsDir apiIdtIndicatorsDir1 = listChildren.get(j);
                    if ("constraint".equals(apiIdtIndicatorsDir1.getApiIndicatorsVal().getAttribute())) {
                        xh++;
                        String indicatorsId = apiIdtIndicatorsDir1.getApiIndicatorsVal().getId();
                        String indicatorsName = apiIdtIndicatorsDir1.getName();
                        String monitorValue = apiIdtIndicatorsDir1.getApiIndicatorsVal().getMonitorValue();
                        String baseValue = apiIdtIndicatorsDir1.getApiIndicatorsVal().getBaseValue();
                        String targetValue = apiIdtIndicatorsDir1.getApiIndicatorsVal().getTargetValue();
                        String unit = apiIdtIndicatorsDir1.getApiIndicatorsVal().getUnit();
                        String warnStatus = apiIdtIndicatorsDir1.getApiIndicatorsVal().getWarnStatus();
                        zxh++;
                        List<String> warnDivisionText = new ArrayList<>();
                        //替换描述字符串
                        String describeText = "";
                        //获取下级行政区划数据
                        List<ApiMapDivision> mapDivisionList = monitorEvaluateWarningMapper.getDivisionByParentCode(divisionCode);
                        html_str += ("<h3 style=\"font-family:'宋体';font-size:16px\">" + (zxh) + "、" + indicatorsName + "</h2>\n" + "<p style=\"text-indent:2em\">" + indicatorsName + "监测值为" + (monitorValue + unit) + "，基期值为" + (baseValue + unit) + "，规划值为" + (targetValue + unit) + "，指标状态为" + warnStatus + "。" + indicatorsId + "具体情况如下：</p>\n");
                        //获取echart
                        String base64Str = generateEChartBase64Str(indicatorsId, divisionCode, Integer.parseInt(year), unit);
                        html_str += ("<img style=\"text-align:center;display:table-cell\" src=\"data:image/png;base64," + base64Str + "\">");
                        html_str += ("<table style =\"border-collapse:collapse\"><tr><th colspan=\"5\" style=\"background: #ccecff;text-align:left\">" + year + "年" + divisionText + "指标监测情况</th></tr><tr><th>序号</th><th>行政区</th><th>监测值</th><th>规划值（2020）</th><th>预警状态</th></tr>");
                        for (int k = 0; k < mapDivisionList.size(); k++) {
                            ApiMapDivision apiMapDivision = mapDivisionList.get(k);
                            ApiIndicatorsVal apiIndicatorsValNext = iIdtIndicatorsService.getIdtVal(indicatorsId, year, apiMapDivision.getCode(), false, false);
                            html_str += ("<tr><td>" + (k + 1) + "</td><td>" + apiMapDivision.getName() + "</td><td>" + apiIndicatorsValNext.getMonitorValue() + "</td><td>" + apiIndicatorsValNext.getTargetValue() + "</td>");
                            if ("预警".equals(apiIndicatorsValNext.getWarnStatus())) {
                                warnDivisionText.add(apiMapDivision.getName());
                                html_str += ("<td style=\"color:red\">预警</td></tr>");
                            } else if ("正常".equals(apiIndicatorsValNext.getWarnStatus())) {
                                html_str += ("<td style=\"color:green\">正常</td></tr>");
                            } else {
                                html_str += ("<td style=\"color:grey\">null</td></tr>");
                            }
                        }
                        html_str += ("</table>");
                        if (warnDivisionText.size() > 0) {
                            describeText += "" + divisionText + "总共有" + mapDivisionList.size() + "个区县，其中有" + warnDivisionText.size() + "个" + divisionLevel + "出现预警状态，分别为";
                            for (int k = 0; k < warnDivisionText.size(); k++) {
                                if (k == 0) {
                                    describeText += (warnDivisionText.get(k));
                                } else {
                                    describeText += ("、" + warnDivisionText.get(k));
                                }
                            }
                            describeText += "。";
                            html_str = html_str.replaceAll(indicatorsId + "", describeText);
                        } else {
                            html_str = html_str.replaceAll(indicatorsId + "", "");
                        }
                        Map map = new HashMap();
                        map.put("XH", xh);
                        map.put("ZBFL", bigName);
                        map.put("ZBMC", indicatorsName);
                        map.put("JCZ", monitorValue);
                        map.put("JQZ", baseValue);
                        map.put("GHZ", targetValue);
                        map.put("DW", unit);
                        if ("预警".equals(warnStatus)) {
                            warningNumber++;
                            map.put("FZCYJZT", warnStatus);
                            map.put("ZCYJZT", "");
                        } else if ("正常".equals(warnStatus)) {
                            map.put("FZCYJZT", "");
                            map.put("ZCYJZT", warnStatus);
                        } else {
                            map.put("FZCYJZT", "");
                            map.put("ZCYJZT", "");
                        }
                        table2.add(map);
                    }
                }
            }
            keyXh.add(xh);
            //域单值字段
            List<Map<String, Object>> fieldTable = new ArrayList<>();
            Map<String, Object> map1 = new HashMap<>();
            map1.put("ZZBX", xh);
            map1.put("YJZBX", warningNumber);
            map1.put("XZQ", divisionText);
            map1.put("XZQJB", divisionLevel);
            fieldTable.add(map1);
            Map<String, Object> map11 = new HashMap<>();
            map11.put("name", "dz");
            map11.put("table", fieldTable);
            fieldData.add(map11);
            Map<String, Object> mapHtml22 = new HashMap<>();
            mapHtml22.put("name", "wwa");
            mapHtml22.put("type", "html");
            ArrayList htmlTable = new ArrayList();
            Map htmlMap = new HashMap();
            htmlMap.put("html_str", html_str);
            htmlTable.add(htmlMap);
            mapHtml22.put("table", htmlTable);
            fieldData.add(mapHtml22);
            //子表列表字段
            //列表数据
            List<Map<String, Object>> tableData2 = new ArrayList<>();
            Map map22 = new HashMap();
            map22.put("name", "ZBMX");
            map22.put("table", table2);
            tableData2.add(map22);
            //进行表格单元格合并
            List<Map<String, Object>> mergeTableList = new ArrayList<>();
            Map<String, Object> mergeTableMap = new HashMap<>();
            mergeTableMap.put("xh", 0);
            List<Map<String, Object>> cellList = new ArrayList<>();
            for (int i = 0; i < keyXh.size() - 1; i++) {
                Map<String, Object> mapRowCell = new HashMap<>();
                String rowCells = (keyXh.get(i) + 1) + "," + "1" + "," + (keyXh.get(i + 1)) + "," + "1";
                mapRowCell.put("rowCell", rowCells);
                cellList.add(mapRowCell);
            }
            mergeTableMap.put("cells", cellList);
            mergeTableList.add(mergeTableMap);
            ClassPathResource resource = new ClassPathResource("template/国土空间规划监测预警报告模板.docx");
            InputStream inputStream1 = resource.getInputStream();
            //进行word打印
            exportFilePath = NewWordUtil.wordprint(inputStream1, fieldData, tableData2, null, "docx", "", "",mergeTableList);
            exportFilePath = exportFilePath.substring(exportFilePath.lastIndexOf("/") + 1, exportFilePath.length());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return exportFilePath;
    }

    *//**
    * @描述: 生成对应的Echart图片base64字符串
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/11/24 11:28
    **//*
    public String generateEChartBase64Str(String idtId, String divisionCode, Integer year, String idtUnit) {
        String base64Str = "";
        //获取近五年的指标数值
        String recentYear = (year - 4) + ","+(year - 3) + ","+(year - 2) + ","+(year - 1) + ","+(year);
        //近五年监测值
        List<String> monitorValueArray = new ArrayList<>();
        //近五年规划值
        List<String> targetValueArray = new ArrayList<>();
        //获取进五年的指标数据
        List<ApiIndicatorsVal> apiIndicatorsVals = iIdtIndicatorsService.listSingleIdtVal(idtId, recentYear, divisionCode, true, false);
        monitorValueArray = apiIndicatorsVals.stream().map(x -> x.getMonitorValue()).collect(Collectors.toList());
        targetValueArray = apiIndicatorsVals.stream().map(x -> x.getTargetValue()).collect(Collectors.toList());
        //生成echart图片
        HashMap<String, Object> datas = new HashMap<>();
        datas.put("recentYear", JSON.toJSONString(recentYear));
        datas.put("unit", idtUnit);
        datas.put("monitorValue", JSON.toJSONString(monitorValueArray));
        datas.put("targetValue", JSON.toJSONString(targetValueArray));
        datas.put("ftl", "option.ftl");
        String option;
        try {
            option = FreemarkerUtil.generateString((String) datas.get("ftl"), "/template", datas);
            String eChartPath = EchartGenerateUtil.generateEChart(option);
            base64Str = ByteToFileUtils.encodeBase64File(eChartPath);
            //删除文件
            FileUtil.deleteFile(eChartPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64Str;
    }

    *//**
     * @描述: 将空字符串转成中横线“ - ”
     * @入参: value 原字符串
     * @入参: defaultValue 源字符串为空时返回的内容
     * @出参:
     * @作者: 陈宏成
     * @日期: 2021/01/14
     **//*
    private String convertNullStringToLine(String value,String defaultValue){
        return StringUtils.isNotBlank(value)?value: defaultValue != null ? defaultValue: " - ";
    }
    *//**
     * @描述: 保留两位小数
     * @入参: value 原字符串
     * @出参: 如果value为空，返回空字符串，否则保留两位小数
     * @作者: 陈宏成
     * @日期: 2021/01/14
     **//*
    private String holdTwoDecimal(String value){
        if(!StringUtils.isNotBlank(value)){
            return "";
        }
        return ConvertUtil.formatNumber(Double.valueOf(value), 2);
    }*/
}
